package dk.contix.ant.gwt;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Util {

	public static boolean hasModifiedFiles(File base, String module, String destDir) {
		File f = new File(base, module);
		Set paths = findSourcedirs(readFile(f));

		boolean foundNew = false;
		long time = 0;
		for (Iterator i = paths.iterator(); i.hasNext();) {
			String path = (String) i.next();
			File sourceDir = new File(f.getParentFile(), path);
			if (sourceDir.isDirectory()) {
				time = Math.max(time, findLatestModificationTime(sourceDir, time));
			}
		}

		String m = module.replaceAll(".gwt.xml", "").replace(File.separatorChar, '.');
		String nocacheFilename = m + File.separator + m + ".nocache.js";
		File output = new File(destDir, nocacheFilename);
		if (output.exists()) {
			foundNew = output.lastModified() > time;
		}
		return !foundNew;
	}

	private static long findLatestModificationTime(File dir, long time) {
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isDirectory()) {
				time = findLatestModificationTime(files[i], time);
			} else if (files[i].getName().endsWith(".java")){
				time = Math.max(time, files[i].lastModified());
			}
		}
		return time;
	}

	private static Set findSourcedirs(String xml) {
		Set res = new HashSet();
		res.add("client");
		int pos = -1;
		while ((pos = xml.indexOf("<source ", pos)) > -1) {
			int ppos = xml.indexOf(" path=", pos + 6);
			if (ppos > -1) {
				char sep = xml.charAt(ppos + 6);
				res.add(xml.substring(ppos + 7, xml.indexOf(sep, ppos + 7)));
			}

			pos += 7;
		}
		return res;
	}

	public static String readFile(File f) {
		StringBuffer sb = new StringBuffer((int) f.length());
		try {
			BufferedReader reader = new BufferedReader(new FileReader(f));
			String l = null;
			while ((l = reader.readLine()) != null) {
				sb.append(l);
			}

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}


}
